﻿using Alta.Class;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Camera_CMD
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        const int TIME_SLEEP = 3000;
        const int BAUDRATE = 9600;
        const int DATABITS = 8;
        private List<SerialPort> listSerialPort;
        private SerialPort serialPort;
        private bool flagconnect = false;
        private string comName = "";
        private string cmd = "";
        private Thread sqlThread;
        private Command command;
        public MainWindow()
        {
            InitializeComponent();
            this.listSerialPort = new List<SerialPort>();
            sqlThread = new Thread(RunMysqlThread);
            sqlThread.IsBackground = true;
         //   sqlThread.Start();
            if (App.setting.mode == AppMode.AUTO)
            {
                this.UIList_COM.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                this.UIList_COM.Visibility = System.Windows.Visibility.Visible;
            }
        }

        private void RunMysqlThread(object obj)
        {
            while (true)
            {
                if (command == null || command.mode == CommandMode.RUN)
                {
                    command = mysql_helpper.getCommand();
                    if (command != null)
                    {
                        Console.WriteLine(command.content);
                    }
                    else
                    {
                        Console.WriteLine("Null");
                    }
                }
                Thread.Sleep(TIME_SLEEP);
            }
        }

      

        private string[] getListCOM()
        {
            
            try
            {
              return System.IO.Ports.SerialPort.GetPortNames().OrderBy(m=>m).ToArray();
            }
            catch (Exception)
            {
                return new string[0];
            }
        }

        private void Window_Load(object sender, RoutedEventArgs e)
        {
            var listCom=getListCOM();
            if (listCom.Length>0)
            {
                foreach(string i in listCom)
                {
                    this.UIList_COM.Items.Add(i);
                }
                
                if (App.setting.mode == AppMode.AUTO)
                {
                    foreach(string i in listCom)
                    {
                        SerialPort serialPort = new SerialPort();
                        serialPort = new SerialPort();
                        serialPort.openCOM(i, BAUDRATE, DATABITS, StopBits.One);
                        serialPort.DataReceived += serialPort_DataReceived;
                        serialPort.sendCommand("#0$");                       
                        this.listSerialPort.Add(serialPort);
                    }
                }
            }
        }

        private void openCOM(string nameCOM, int baurate, int databits, StopBits @StopBits= StopBits.One)
        {
            try
            {                
                serialPort = new SerialPort();              
                serialPort.openCOM(nameCOM, baurate, databits, StopBits);
                serialPort.DataReceived += serialPort_DataReceived;
                this.serialPort.sendCommand("#0$");
            }
            catch (Exception ex)
            {

            }
        }

        private void closeCOM()
        {
            if (this.serialPort.IsOpen)
            {
                while (this.serialPort.BytesToWrite > 0) { }
                this.serialPort.Dispose();
                this.serialPort.Close();

            }
        }

        private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            bool flag = true;
            char[] charsToTrim = {'\n' };
            SerialPort s = sender as SerialPort;
            string tmp = s.ReadExisting().Trim(charsToTrim);
            if (tmp.IndexOf("#") >= 0)
            {
                this.cmd = string.Empty;
                this.cmd += tmp;
                flag = false;
            }
            if (tmp.IndexOf("$") >= 0)
            {
                this.cmd += tmp;
                mysql_helpper.setCommand(this.cmd,s.PortName.ToString());
                char[] tmpS = { ' ' };
                string[] element = this.cmd.Split(tmpS);
                Console.WriteLine(this.cmd);
                Regex myRegex = new Regex(@"\w$");
                if (!myRegex.IsMatch(this.cmd) && !string.IsNullOrEmpty(this.cmd))
                {
                    //s.sendCommand(element[0] + " OK$");
                }
                flag = false;
                this.cmd = string.Empty;
            }
            if(flag)
                this.cmd += tmp;            
        }

        private void UIList_COM_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this.comName = (string)(sender as ComboBox).SelectedItem;
            //string value = typeItem.Content.ToString();
          //  this.comName = typeItem.Content.ToString();
            if (!string.IsNullOrEmpty(this.comName))
            {
                if (!flagconnect)
                {
                    this.openCOM(comName, BAUDRATE, DATABITS);
                }
                else
                {
                    this.closeCOM();
                    this.openCOM(comName, BAUDRATE, DATABITS);
                }
            }
        }

        private void Window_KeyUp(object sender, KeyEventArgs e)
        {
            if (Key.E == e.Key)
            {
                if (this.command != null)
                {
                    this.command.mode = CommandMode.RUN;
                }
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string cmd = this.UIcommand.Text;
            if(!string.IsNullOrEmpty(cmd))
            {
                foreach (SerialPort s in this.listSerialPort)
                {
                    if (s.IsOpen)
                        s.sendCommand(cmd);
                }
            }
        }
    }
}
